<?php
/**
 * Created by b17
 * 2/17/12 8:39 PM
 */

namespace Managers;

use G4T\Util\ArrayUtil;

class Marks extends BaseManager
{
    const TABLE = '\Catalog\Marks';
    protected $__table = self::TABLE;

    protected function createQueryBuilder()
    {
        $qb = parent::createQueryBuilder()
            ->select('m, n')
            ->from($this->__table, 'm')
            ->join('m.news', 'n')
            ->andWhere('n.isDel = 0');
        return $qb;
    }

    public function getNewsRating($newsId)
    {
        $qb = $this->createQueryBuilder()
            ->select('sum(m.mark) as total_sum, count(m.id) as total_count')
            ->andWhere('n.id = :news')->setParameter('news', $newsId);
        $res = $qb->getQuery()->getArrayResult();
        $totalCount = $res[0]['total_count'] > 0 ? $res[0]['total_count'] : 1;
        return floor($res[0]['total_sum'] / $totalCount);
    }

    public function injectMarks($news)
    {
        if (0 == count($news)) {
            return $news;
        }
        $qb = $this->createQueryBuilder()
            ->select('sum(m.mark) as total_sum, count(m.id) as total_count, n.id as news')
            ->addGroupBy('n.id');
        $newsIds = ArrayUtil::matchesRebuild($news);
        $qb->andWhere($qb->expr()->in('n.id', $newsIds));

        $res = $qb->getQuery()->getArrayResult();
        foreach ($news as &$article) {
            $article['mark'] = 0;
            foreach ($res as $mark) {
                if ($mark['news'] == $article['id']) {
                    $totalCount = $mark['total_count'] > 0 ? $mark['total_count'] : 1;
                    $article['mark'] = floor($mark['total_sum'] / $totalCount);
                }
            }
        }
        return $news;
    }


    public function canVote($newsId, $ip)
    {
        if (is_null($newsId)) {
            return false;
        }
        $ip = ip2long($ip);
        $qb = $this->createQueryBuilder()
            ->andWhere('m.ip = :ip')->setParameter('ip', $ip)
            ->andWhere('n.id = :news')->setParameter('news', $newsId);
        $res = $qb->getQuery()->getArrayResult();
        return count($res) == 0;
    }

    public function vote($newsId, $ip, $mark)
    {
        $entity = new \Catalog\Marks();
        $entity->setIp(ip2long($ip));
        $newsRef = $this->_em->getReference(News::TABLE, $newsId);
        if (!$newsRef) {
            return false;
        }
        $entity->setNews($newsRef);
        $entity->setMark($mark);
        $this->_em->persist($entity);
        $this->flush();
        return $entity;
    }


}
